package com.basic.common.utils;

import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import java.security.SecureRandom;
import java.util.Base64;

public class PasswordUtil {

    // 生成随机盐
    public static String generateSalt() {
        SecureRandom random = new SecureRandom();
        byte[] salt = new byte[16]; // 16字节盐
        random.nextBytes(salt);
        return Base64.getEncoder().encodeToString(salt); // 将盐编码为Base64字符串
    }

    // 加盐MD5加密
    public static String encryptPasswordWithSalt(String password) {
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        return encoder.encode(password);
    }

    public static Boolean matchesPass(String password, String encodedPassword){
        return new BCryptPasswordEncoder().matches(password, encodedPassword);
    }

    public static void main(String[] args) {
        String s = "123456";
        System.out.println(s);
        String s1 = encryptPasswordWithSalt("123456");
        String s2 = encryptPasswordWithSalt("123456");
        System.out.println(s1);

        boolean matches = new BCryptPasswordEncoder().matches(s, s1);
        boolean matches1 = new BCryptPasswordEncoder().matches(s, s2);

        System.out.println(matches);
        System.out.println(matches1);
    }

}
